package com.open.httpauto;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.open.httpauto.http.Http;
import org.yaml.snakeyaml.Yaml;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public enum HttpYamlHandler {
    Instance;

    public static void main(String[] args) {
        List<Http> httpList = HttpYamlHandler.Instance.getHttpAll();
        System.out.println(JSON.toJSONString(httpList, JSONWriter.Feature.PrettyFormat));

        Http http = HttpYamlHandler.Instance.getHttp("demo1");
        System.out.println(JSON.toJSONString(http, JSONWriter.Feature.PrettyFormat));
    }

    /**
     * 配置文件路径
     */
    private static String ROOT_PATH_YML = "autohttp";

    private static String ROOT = "http";

    /**
     * 根据 httpId 读取 yaml 配置文件
     *
     * @param httpId
     * @return
     */
    public Http getHttp(String httpId) {
        List<Http> httpList = this.getHttpAll();
        if (CollectionUtil.isEmpty(httpList)) {
            return null;
        }

        Map<String, Http> map = httpList.stream().collect(Collectors.toMap(Http::getId, Function.identity()));
        Http http = map.get(httpId);
        return http;
    }

    /**
     * 获取 httpList
     * 要求 httpId 全局唯一否则自动覆盖
     *
     * @return List<Http>
     */
    public List<Http> getHttpAll() {
        List<String> listFileNames = FileUtil.listFileNames(ROOT_PATH_YML);
        List<Http> httpList = new ArrayList<>();

        Yaml yaml = new Yaml();
        for (String listFileName : listFileNames) {
            Map<String, List<Map<String, Object>>> httpMap = null;
            try {
                httpMap = yaml.loadAs(HttpYamlHandler.class.getResourceAsStream("/" + ROOT_PATH_YML + "/" + listFileName), Map.class);
            } catch (Exception e) {
            }

            if (null == httpMap) {
                return null;
            }
            List<Map<String, Object>> mapList = httpMap.get(ROOT);
            List<Http> list = Convert.toList(Http.class, mapList);
            httpList.addAll(list);
        }

        return httpList;
    }


}
